import { IS_IOS } from './environment'
// const IS_IOS = true

let firstVisitUrl = ''

function getLocalPath () {
  return location.href.split('#')[0]
}

/**
 * 微信分享适配
 *
 * @export
 * @class WechatAdapter
 */
export class WechatAdapter {
  private wx
  private _wechatConfig
  private shareApiList: string[]
  private featureApiList: string[]
  private debug: boolean
  private _shareSettings
  private promiseFunc: (any?) => Promise<any>

  constructor(wx, options) {
    this.wx = wx
    this.debug = options.debug || false
    this.shareApiList = options.shareApiList
    this.featureApiList = options.featureApiList
    this.promiseFunc = options.promiseFunc

    // this.init()
  }

  init () {
    this.setupReady()
  }

  /**
   * 更新
   *
   * @param {any} shareSettings
   * @param {any} [signOptions]
   * @memberof WechatAdapter
   */
  update(shareSettings) {
    this.shareSettings = shareSettings

    if (IS_IOS) return this.iosUpdate(shareSettings)

    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(), 500)
    }).then(() => this.normalUpdate(shareSettings, getLocalPath()))
  }

  async iosUpdate(shareSettings) {
    if (!firstVisitUrl) {
      firstVisitUrl = getLocalPath()
      return await this.normalUpdate(shareSettings, firstVisitUrl)
    }

    return Promise.resolve(this.setupReady())
  }

  async normalUpdate(shareSettings, url) {
    const settings = await this.promiseFunc({ url })

    this.setupReady()
    this.setupConfig(settings)
    return settings
  }

  async specialUpdate() {
    const settings = await this.promiseFunc({ firstVisitUrl })

    this.setupConfig(settings)
    return settings
  }

  /**
   * 分享配置
   *
   * @memberof WechatAdapter
   */
  get shareSettings() {
    return this._shareSettings
  }
  set shareSettings(settings) {
    this._shareSettings = settings
  }

  /**
   * 设置回调
   *
   * @param {any} configs
   * @memberof WechatAdapter
   */
  setupReady() {
    const { wx } = this
    console.log('setup ready')

    wx.ready(() => {
      console.log('into ready')
      this.setupShareAPIList(this.shareSettings)
    })
  }

  /**
   * 安装微信设置
   *
   * @param {any} signOptions
   * @memberof WechatAdapter
   */
  setupConfig(signOptions) {
    const { wx, debug, shareApiList, featureApiList } = this

    wx.config({
      debug,
      ...signOptions,
      jsApiList: [...shareApiList, ...featureApiList]
    })
  }


  /**
   * 设置微信分享信息
   *
   * @memberof WechatAdapter
   */
  setupShareAPIList(configs) {
    const { wx, shareApiList } = this

    shareApiList.forEach(funcName => wx[funcName](configs))
  }
}
